import { BasicLayout, RouteView } from '@/layouts'
import icons from '@/utils/menuIcons'
// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*', redirect: '/404', hidden: true
}

// 根级菜单
const rootRouter = {
  id: '-1',
  name: 'index',
  path: '/',
  component: BasicLayout,
  redirect: '/sys/menu/index',
  meta: {
    title: '首页'
  },
  children: []
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (result) => {
  return new Promise((resolve, reject) => {
    const menuNav = []
    const childrenNav = []
    //      后端数据, 根级树数组,  根级 PID
    listToTree(result, childrenNav, '0')
    rootRouter.children = childrenNav
    // rootRouter.redirect = rootRouter.children[0].path
    menuNav.push(rootRouter)
    const routers = generator(menuNav)
    routers.push(notFoundRouter)
    resolve(routers)
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const currentRouter = {
      path: item.path || `/${item.id}`,
      // 路由名称，建议唯一
      name: `m${item.id}`,
      // meta: 页面标题, 菜单图标
      meta: {
        title: (item.meta || {}).title || item.title,
        icon: (item.meta || {}).icon || icons[item.icons],
        keepAlive: true
        // hiddenHeaderContent: hiddenHeaderContent,
        // target: target
      }
    }
    currentRouter.path = currentRouter.path.replace('//', '/')
    if (item.menuType === 1) {
      currentRouter.component = RouteView
    } else if (item.menuType === 2) {
      currentRouter.component = resolve => require([`@/views${item.path}`], resolve)
    } else {
      if (item.component) {
        currentRouter.component = item.component
      }
    }
    // 是否设置了隐藏菜单
    // if (item.show === false) {
    //   currentRouter.hidden = true
    // }
    // 是否设置了隐藏子菜单
    // if (hideChildren) {
    //   currentRouter.hideChildrenInMenu = true
    // }
    // 重定向
    // currentRouter.redirect = item.children && item.children[0].url
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      /* 设置跳转第一个节点 */
      currentRouter.redirect = item.children[0].path || `/${item.children[0].id}`
      // 递归
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param pid 父ID
 */
const listToTree = (list, tree, pid) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.pid === pid) {
      const child = {
        ...item,
        key: item.id,
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      if (item.menuType === 1) {
        listToTree(list, child.children, item.id)
      }
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}
